package com.remote.ui.event;


import com.remote.common.command.Commands;
import com.remote.common.exception.RemoteException;
import com.remote.common.model.ClientInfo;
import com.remote.common.model.fx.MasterKeyEvent;
import com.remote.ui.constant.UIConstant;
import com.remote.ui.core.Controller;
import javafx.scene.input.KeyEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author Cool-Coding
 * 2018/7/26
 */
public class KeyBoardHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(KeyBoardHandler.class);

    private final Controller controller;

    public KeyBoardHandler(Controller controller) {
        this.controller = controller;
    }


    public void keyPressed(KeyEvent e) {
//        LOGGER.debug(e.getCode().getName() + " pressed");
        fireCommand(e, true);
    }


    public void keyReleased(KeyEvent e) {
//        LOGGER.debug(e.getCode().getName() + " released");
        fireCommand(e, false);
    }

    private void fireCommand(KeyEvent e, boolean pressed) {
        final MasterKeyEvent keyEvent = new MasterKeyEvent();
        keyEvent.setPressed(pressed);
        if (e.isAltDown()) {
            keyEvent.setAltDown(true);
        }
        if (e.isControlDown()) {
            keyEvent.setCtrlDown(true);
        }
        if (e.isShiftDown()) {
            keyEvent.setShiftDown(true);
        }
        keyEvent.setKeyCode(e.getCode().impl_getCode());
        try {
            ClientInfo clientInfo = (ClientInfo) controller.getValue(UIConstant.P_CLIENT_INFO);
            controller.getControllerManager().getCommandContext().fireCommand(clientInfo.getClientId(), Commands.KEYBOARD, keyEvent);
        } catch (RemoteException e2) {
            controller.showMessage("异常", e2.getMessage());
        }
    }
}
